package com.zdb.n1.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.OptBoolean;
import jakarta.persistence.*;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table(name = "exercise_records")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExerciseRecord {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    @JsonIgnoreProperties({"password", "roles"})
    private User user;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "exercise_type_id", nullable = false)
    private ExerciseType exerciseType;

    @NotNull
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date startTime;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date endTime;

    @Positive
    private Integer durationMinutes; // 运动时长（分钟）

    private Double caloriesBurned; // 消耗的卡路里

    private String notes; // 备注，如感受、强度等

    @Enumerated(EnumType.STRING)
    private Intensity intensity = Intensity.MEDIUM;

    private String location; // 运动地点

    @PrePersist
    @PreUpdate
    public void calculateValues() {
        // 根据开始和结束时间计算时长
        if (startTime != null && endTime != null) {
            long minutesBetween = (endTime.getTime() - startTime.getTime()) / (60 * 1000);
            durationMinutes = (int) minutesBetween;
        }

        // 计算卡路里消耗
        if (durationMinutes != null && exerciseType != null && exerciseType.getCaloriesPerMinute() != null) {
            double intensityMultiplier = getIntensityMultiplier();
            caloriesBurned = durationMinutes * exerciseType.getCaloriesPerMinute() * intensityMultiplier;
            // 四舍五入到两位小数
            caloriesBurned = Math.round(caloriesBurned * 100.0) / 100.0;
        }
    }

    private double getIntensityMultiplier() {
        switch (intensity) {
            case LOW:
                return 0.8;
            case MEDIUM:
                return 1.0;
            case HIGH:
                return 1.2;
            case VERY_HIGH:
                return 1.5;
            default:
                return 1.0;
        }
    }

    public enum Intensity {
        LOW("低强度"),
        MEDIUM("中等强度"),
        HIGH("高强度"),
        VERY_HIGH("极高强度");

        private final String displayName;

        Intensity(String displayName) {
            this.displayName = displayName;
        }

        public String getDisplayName() {
            return displayName;
        }
    }
} 